package com.glodon.paas.framework.registry.server.health;

import com.glodon.paas.framework.registry.server.ServerManager;
import com.glodon.paas.framework.registry.server.exception.RegistryServerRuntimeException;
import com.glodon.paas.framework.registry.server.zk.util.ZooKeeperServerUtils;
import com.glodon.paas.framework.registry.server.zk.watcher.ServiceRootWatcher;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Scan the zk cluster at server initialization time and set the corresponding status for each services, apps etc.
 *
 * @author Don Li
 */
public class NodeScanner {
    private final Logger LOGGER = LoggerFactory.getLogger(NodeScanner.class);

    private String servicesPath;
    private String appsPath;
    private String configsPath;

    private ServerManager manager;

    public void setServicesPath(String servicesPath) {
        this.servicesPath = servicesPath;
    }

    public void setAppsPath(String appsPath) {
        this.appsPath = appsPath;
    }

    public void setConfigsPath(String configsPath) {
        this.configsPath = configsPath;
    }

    public void scanAll() {
        try {
            scanAllServices();
            scanAllApps();
            scanAllConfigs();
        } catch (Exception e) {
            LOGGER.error("Error scaning znodes, NodeScanner fail to initialize");
            throw new RegistryServerRuntimeException(e);
        }
        LOGGER.info("Scanning successfully");
    }

    public void setManager(ServerManager manager) {
        this.manager = manager;
    }

    private void scanAllServices() throws KeeperException, InterruptedException {
        ZooKeeper zk = manager.getZk();
        // watch the changes of service
        List<String> services = zk.getChildren(servicesPath, new ServiceRootWatcher(zk));
        for (String service : services) {
            ZooKeeperServerUtils.updateServiceStatus(zk, servicesPath + "/" + service);
        }
    }

    private void scanAllApps() {
        // nothing to do here right now
    }

    private void scanAllConfigs() {
        // nothing to do here right now
    }

}
